#include <stdio.h>

#define N 10
/**
 * File: Exercise1007.c
 * -------------------------------------------------------
 * 1.7 Do Exercise 1.4, but use the weighted quick-union algorithm (Program 1.3).
 * -------------------------------------------------------
 * 输入
 * 0 2 1 4 2 5 3 6 0 4 6 0 1 3
 * -------------------------------------------------------
 * 出处：[WeightedQuickUnion.c](https://gitcode.com/haoly1989/books/blob/main/AlgorithmsInC/examples/chapter1/WeightedQuickUnion.c)
 */
int main(int argc, char **argv){
    int i, p, q, j;
    int id[N];
    int sz[N];

    for (i = 0; i < N; i++) {
        id[i] = i;
        sz[i] = 1;
    }

    while (scanf("%d %d\n", &p, &q) == 2) {
        int count = 0;
        for (i = p; i != id[i]; i = id[i]) {
            count+=2;
            ;
        }
        //寻找q所在树的根节点，用j来记录
        for (j = q; j != id[j]; j = id[j]) {
            count+=2;
            ;
        }
        if (i == j) {
            //如果i==j(p所在树的根节点等于q所在树的根节点)，即set(p)和set(q)相等，则表示p和q相连
            continue;
        }
        if (sz[i] < sz[j]) {
            id[i] = j;
            sz[j] += sz[i];
        }else {
            id[j] = i;
            sz[i] += sz[j];
        }
        count+=5;
        // printf("%d %d\n", p, q);
        for (int k = 0; k < N; k++) {
            printf("%d ", id[k]);
        }
        printf("\n");
        printf("%d-%d access array %d times\n", p, q, count);
    }
    return 0;
}

//每次union后，id数组的内容
//输入：0 2 1 4 2 5 3 6 0 4 6 0 1 3
// 0 1 0 3 4 5 6 7 8 9 
// 0-2 access array 5 times
// 0 1 0 3 1 5 6 7 8 9 
// 1-4 access array 5 times
// 0 1 0 3 1 0 6 7 8 9 
// 2-5 access array 7 times
// 0 1 0 3 1 0 3 7 8 9 
// 3-6 access array 5 times
// 0 0 0 3 1 0 3 7 8 9 
// 0-4 access array 7 times
// 0 0 0 0 1 0 3 7 8 9 
// 6-0 access array 7 times